﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace cludg.Repository.Security.InMemory
{
    using Domain.Users;

    public class SecurityRepository : ISecurityRepository
    {
        protected static readonly List<User> Users = new List<User>();
        protected static readonly List<UserSecurityInfo> UserSecurityInfos = new List<UserSecurityInfo>();

        public IEnumerable<User> AllUsers
        {
            get { return Users; }
        }

        public User GetUserById(string userId)
        {
            return Users.FirstOrDefault(u => u.Id == userId);
        }

        public UserSecurityInfo GetUserSecurityInfoByName(string userName)
        {
            return UserSecurityInfos.FirstOrDefault(i => i.Name == userName);
        }

        public UserSecurityInfo GetUserSecurityInfoByEmail(string email)
        {
            return UserSecurityInfos.FirstOrDefault(i => i.Email == email);
        }

        public UserSecurityInfo GetUserSecurityInfoByThirPartyIdent(string ident)
        {
            return UserSecurityInfos.FirstOrDefault(i => i.ThirdPartyIdent == ident);
        }

        public UserSecurityInfo GetUserSecurityInfo(string id)
        {
            return UserSecurityInfos.FirstOrDefault(i => i.Id == id);
        }

        public string AddUser(User user)
        {
            if (String.IsNullOrEmpty(user.Id))
            {
                user.Id = Utils.Identity.Generate();
            }
            else
            {
                if (GetUserById(user.Id) != null)
                    throw new ApplicationException("Пользователь уже есть!");
            }

            Users.Add(user);

            return user.Id;
        }

        public void ChangeUserSecurityInfo(string userId, UserSecurityInfo info)
        {
            if (GetUserById(userId) == null)
                throw new ApplicationException("Пользователя нет!");

            UserSecurityInfo prevInfo = GetUserSecurityInfo(userId);
            if (prevInfo != null)
                UserSecurityInfos.Remove(prevInfo);

            info.Id = userId;
            UserSecurityInfos.Add(info);
        }

        public void SaveUser(string userId, User user)
        {
            User prevUser = GetUserById(userId);
            if (prevUser != null)
                Users.Remove(prevUser);

            user.Id = userId;
            Users.Add(user);
        }
    }
}
